package main

import (
	"go_user_manager/pkg/adapters/agin"
	"go_user_manager/pkg/framework"
	"go_user_manager/pkg/utils/observability/log"
	"go_user_manager/pkg/utils/observability/metrics"
	"go_user_manager/pkg/utils/observability/tracing"

	"github.com/spf13/cobra"
)

var (
	rootCmd     = &cobra.Command{}
	cfgFilePath string
)

func main() {
	// 加载配置文件
	cfg := Config{}
	rootCmd.PersistentFlags().StringVarP(&cfgFilePath, "config", "c", "", "config file (default is ./config/config.yaml)")
	_ = rootCmd.Execute()

	if cfgFilePath == "" {
		cfgFilePath = "./configs/config-dev.yaml"
	}
	err := framework.LoadConfiguration(cfgFilePath, "", &cfg)
	// 测试环境
	//err := framework.LoadConfiguration("./configs/config-dev.yaml", "", &cfg)
	if err != nil {
		panic(err)
	}
	// 初始化logger
	logger := log.NewLogger(cfg.Log)
	// 创建metrics
	meter := metrics.NewMetrics(logger)
	// 初始化tracing
	tracing.InitTracer(&cfg, logger)

	// 初始化ginOption
	ginServer := NewGinServer(logger, &cfg).
		WithOptions(agin.NewOptionsFromConfig(&cfg).
			OptionListenAddr(":8079").
			OptionsMiddlewares(
				agin.LogAccessMiddleware(cfg.Trace.ServiceName, logger),
				//agin.JWTMiddleware(cfg.JWT, logger),
				//agin.SSOHandlerfunc(logger),
			).
			OptionMetrics().
			OptionTrace(),
		)
	// Important: 需要在所有得server option 完成之后进行meter的初始化，
	// 初始换完成之后将会返回一个http.Handler，使用该Handler处理请求
	meter.Init()

	app := framework.NewApp(logger)
	app.WithServer(
		ginServer,
		meter,
	)
	err = app.Start()
	if err != nil {
		logger.Error("app exited", err)
	}
}
